<template>
  <!-- 公共文件上传组件  返回文件流 -->
  <div class="upload">
    <el-upload
      class="avatar-uploader"
      action="false"
      ref="uploadref"
      :accept="accept"
      :auto-upload="false"
      :on-change="handleImgChange"
      :on-remove="handleRemove"
      :limit="limit"
      :file-list="Filelist"
      :on-exceed="handleExceed"
    >
      <template #tip v-if="tip">
        <div class="el-upload__tip">
          {{ tip }}
        </div>
      </template>
      <el-button type="primary">附件上传</el-button>
      <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon> -->
    </el-upload>
  </div>
</template>

<script setup>
import { defineEmits, defineProps, ref } from "vue";
import { ElMessage } from "element-plus";
const emit = defineEmits(["file-uploaded", "file-remove"]);
const props = defineProps({
  // 提示
  tip: {
    type: String,
    default: "",
  },
  limit: {
    type: Number,
    default: 1,
  },
  // 附件id
  uploadId: {
    type: Number,
  },
  // 显示的附件列表
  Filelist: {
    type: Array,
    default: () => [],
  },
  // 上传的附件类型
  accept: {
    type: String,
    default: "",
  },
  //限制大小  M
  maxSize: {
    type: Number,
    default: 10,
  },
  //限制类型 '['image/png','image/gif','image/jpg','image/jpeg']
  fileType: {
    type: Array,
    default: () => [],
  },
});

const uploadref = ref(null);
const handleImgChange = (uploadFile, uploadFiles) => {
  console.log(uploadFile);

  const fileType = props.fileType.includes(uploadFile.raw.type);
  // console.log(fileType);
  const isLt = uploadFile.raw.size / 1024 / 1024 < props.maxSize;
  if (!fileType) {
    ElMessage.error(`上传文件只能是 ${props.accept} 格式!`);
    uploadref.value.clearFiles();
    return false;
  } else if (!isLt) {
    ElMessage.error(`上传的附件大小不能超过 ${props.maxSize}MB!`);
    uploadref.value.clearFiles();
    return false;
  }

  emit("file-uploaded", {
    uploadId: props.uploadId,
    fileData: uploadFiles,
  });
};
const handleRemove = (file, fileList) => {
  emit("file-remove", {
    uploadId: props.uploadId,
    fileData: file,
    fileList: fileList,
  });
};

//文件长度限制
const handleExceed = (files, fileList) => {
  ElMessage.error(`当前限制选择 ${props.limit} 个文件`);
  return false;
};
</script>

<style scoped>
:deep(.el-upload-list__item) {
  width: 400px;
}
</style>
